<?php
/**
 * Class model that provides the base functionality to manage Components data
 *
 * @author Gonzalez Federico, Viera Leonel
 * @package Protoweb
 * @subpackage model
 */
abstract class Component extends PwModel 
{
    public $project;
    public $attributes  = array();

    public function parseAttributes($attributes = null)
    {
        return $attributes;
    }

    public function prepareParse(&$data){}

    public static function getComponent($componentID, $project = null) 
    {
        // get CodeIngiter instace
        $CI =& get_instance();        
        require_once($CI->config->item('components_path')."{$componentID}/{$componentID}.class.php");

        $component = new $componentID($project);

        return $component;
    }

    public static function getAll()
    {
        // get CodeIngiter instace
        $CI =& get_instance();

        // get components from folder
        $components = scandir($CI->config->item('components_path'));

        // remove '.' and '..' entries and reconstruct array index
        $components = array_diff($components, array('.','..'));
        $components = array_values($components);

        // build components array
        $componentsArray = array();
        foreach ($components as $componentName) {
            $componentObj = self::getComponent($componentName);
            array_push($componentsArray, $componentObj);
        }

        return $componentsArray;
    }

    public function __construct($project)
    {
        $this->project = $project;
    }

    public function getDesignView($post = null) 
    {
        $data;
        if ($post) {
            $data = $this->parseAttributes($post);
        }

        $designView = "<pw:component name='{$this->id}' class='pw-component'";
        
        foreach ($this->attributes as $attribute) {

            if(isset($data[$attribute['id']])) {
                $data[$attribute['id']] = htmlspecialchars_decode($data[$attribute['id']]);
                $data[$attribute['id']] = str_replace('"', "'", $data[$attribute['id']]);

                $designView .= ' data-' . $attribute['id'] . '="' . $data[$attribute['id']] . '"';

                if( ((strstr($data[$attribute['id']], '{$'))) ) {
                    $data[$attribute['id']] = $attribute['example'];
                }
                else {
                    $data[$attribute['id']] = $data[$attribute['id']];
                }
            }
            else {
                $data[$attribute['id']] = $attribute['example'];
            }
        }

        $designView .= ">
                        <div class='component-toolbar btn-group'>
                            <a class='btn pw-component-move' title='Move'><i class='icon-move'></i></a> 
                            <a class='btn pw-component-edit' title='Edit'><i class='icon-pencil'></i></a>
                            <a class='btn pw-component-clone' title='Duplicate'><i class='icon-file'></i></a>
                            <a class='btn pw-component-remove' title='Remove'><i class='icon-trash'></i></a>
                        </div>" .
                        $this->parseDesignView($data) . 
                    "</pw:component>\r\n";

        return $designView;
    }

    public function parseDesignView($data) 
    {
        // incluir los valores del campo "example" del json 
        // o un valor aleatorio de la BD

        $data['project'] = $this->project;

        $this->prepareParse($data);

        $CI =& get_instance();
        $CI->smartyview->smarty->assign($data);
        $tpl_parsed = $CI->smartyview->smarty->fetch($this->getComponentPath()."{$this->id}.html");

        if (array_key_exists('pwContainerContent', $data)) {
            $tpl_parsed = str_replace('<pw:container></pw:container>', '<pw:container class="pw-container">'. $data['pwContainerContent'] .'</pw:container>', $tpl_parsed);
        }

        return $tpl_parsed;
    }

    public function getProperties($data)
    {

        $data['project'] = $this->project;

        //die(var_dump($data));

        $CI =& get_instance();
        $CI->smartyview->smarty->assign($data);

        $tpl_parsed = $CI->smartyview->smarty->fetch($this->getComponentPath()."{$this->id}.properties.html");

        return $tpl_parsed;
    }

    public function getStaticJs()
    {
        return file_get_contents($this->getComponentPath()."{$this->id}.static.js");
    }

    public function getInstancesJs()
    {
        return file_get_contents($this->getComponentPath()."{$this->id}.instances.js");
    }

    public function getCss()
    {
        return file_get_contents($this->getComponentPath()."{$this->id}.css");
    }

    private function getComponentPath() 
    {
        $CI =& get_instance();        
        return $CI->config->item('components_path')."{$this->id}/";
    }

    public function parse($data) 
    {
        $data['project'] = $this->project;

        $this->prepareParse($data);

        $CI =& get_instance();
        $CI->smartyview->smarty->assign($data);

        // get component HTML and replace smarty's expressions with literal
        $tpl = file_get_contents($this->getComponentPath()."{$this->id}.html");        
        $tpl = preg_replace('/\{include file="(.+)"\}/', '{literal}{include file="{/literal}$1{literal}"}{/literal}', $tpl);

        //get rid off project_url()
        $tpl = str_replace('{$project->views_path()}', '', $tpl);

        // make a tmp file with the literals
        $tmpFileName = $this->getComponentPath() . 'tmp_' . time() . '.tpl';
        file_put_contents($tmpFileName, $tpl);
        
        // parse the tmp file and delete it
        $tplParsed = $CI->smartyview->smarty->fetch($tmpFileName);
        unlink($tmpFileName);

        if (array_key_exists('pwContainerContent', $data)) {
            $tplParsed = str_replace('<pw:container></pw:container>', $data['pwContainerContent'], $tplParsed);
        }

        return $tplParsed;
    }

    public function getThumbnail() 
    {
        // debe cargar el thumb desde el archivo component.png
        // deberia reducirlo a 80x60
        // si no existe el archivo, devuelve una alternativa

        return base_url() . "assets/img/component-thumbnail.png";    
    }

} // Class Component

/* End of file component.php */
/* Location: ./application/models/component.php */
